<template>
	<view class="category-management">
		<!-- 搜索和添加区域 -->
		<view class="search-bar">
			<uni-search-bar v-model="searchKeyword" placeholder="输入名称" @confirm="handleSearch" @clear="handleSearchClear"
				cancelButton="none" style="flex: 1;" />
			<view class="type-select">
				<uni-data-select v-model="searchType" :localdata="typeOptions" placeholder="全部类型" @change="handleSearch"
					style="width: 200rpx; margin-right: 10rpx;" />
			</view>
			<button class="add-btn" @click="showAddDialog">新增分类</button>
		</view>

		<!-- 分类列表 -->
		<view class="list-container">
			<view v-for="(category,index) in filteredCategories" :key="category._id" class="category-card">
				<view class="card-left">
					<view class="card-header">
						<text class="name"><text class="no">{{index+1}}</text>{{ category.name }}</text>
						<text class="type" :class="category.type===1?'dish-type':'setmeal-type'">
							{{ category.type === 1 ? '菜品分类' : '套餐分类' }}
						</text>
						<text class="status" :class="{ 'status-disabled': category.status === 0 }" @click="toggleStatus(category)">
							{{ category.status === 1 ? '已启用' : '已禁用' }}
						</text>
					</view>
					<view class="card-body">
						<view class="info-item">
							<uni-icons type="sort" size="16"></uni-icons>
							<text>排序: {{ category.sort }}</text>
						</view>
						<view class="info-item">
							<uni-icons type="calendar" size="16"></uni-icons>
							<text>创建时间: {{ formatDate(category.createTime) }}</text>
						</view>
					</view>
				</view>
				<view class="card-right">
					<button class="action-btn edit-btn" @click="showEditDialog(category)">修改</button>
					<button class="action-btn delete-btn" @click="confirmDelete(category._id)">删除</button>
				</view>
			</view>

			<uni-load-more :status="loadStatus" @clickLoadMore="showMoreData"></uni-load-more>
			<view class="safe-area-box"></view>
		</view>

		<!-- 添加/编辑弹窗 -->
		<uni-popup ref="popup" type="dialog" style="z-index: 10;">
			<view class="popup-content">
				<view class="title-box">
					<text class="title-text">{{isEditMode?'修改分类':'添加分类'}}</text>
				</view>
				<view class="form-container">
					<uni-forms ref="form" :model="formData" :rules="rules">
						<uni-forms-item label="分类名称" name="name" label-align="right">
							<uni-easyinput v-model="formData.name" placeholder="请输入分类名称" />
						</uni-forms-item>
						<uni-forms-item label="分类类型" name="type" label-align="right">
							<uni-data-select v-model="formData.type" :localdata="typeOptions" placeholder="请选择分类类型" />
						</uni-forms-item>
						<uni-forms-item label="排序" name="sort" label-align="right">
							<uni-easyinput type="number" v-model="formData.sort" placeholder="请输入排序数字" />
						</uni-forms-item>
					</uni-forms>
				</view>
				<view class="dialog-buttons">
					<button class="dialog-btn cancel-btn" @click="$refs.popup.close()">取消</button>
					<button class="dialog-btn confirm-btn" @click="submitForm">确认</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		addCategory,
		deleteCategory,
		getCategories,
		updateCategory
	} from '../api/category';

	// 分类数据
	const categories = ref([]);
	const searchKeyword = ref('');
	const searchType = ref(0);
	let page = 1;
	let pageSize = 8;
	const loadStatus = ref('more');

	// 弹窗相关
	const popup = ref(null);
	const form = ref(null);
	const isEditMode = ref(false);
	const formData = ref({});

	// 类型选项
	const typeOptions = ref([{
			value: 1,
			text: '菜品分类'
		},
		{
			value: 2,
			text: '套餐分类'
		}
	]);

	// 表单验证规则
	const rules = {
		name: {
			rules: [{
					required: true,
					errorMessage: '请输入分类名称',
				},
				{
					minLength: 2,
					maxLength: 10,
					errorMessage: '分类名称长度在2-10个字符之间'
				}
			]
		},
		type: {
			rules: [{
					required: true,
					errorMessage: '请选择分类类型'
				},
				{
					format: 'number',
					minimum: 1, // 最小值为1
					errorMessage: '请选择分类类型'
				}
			]
		},
		sort: {
			rules: [{
				required: true,
				errorMessage: '请输入排序数字'
			}]
		}
	};

	// 获取列表数据
	const getListData = async (page1 = 0) => {
		if (page1) {
			loadStatus.value = 'more';
			categories.value = [];
			page = page1;
		}
		if (loadStatus.value === 'loading') {
			return;
		}
		if (loadStatus.value === 'no-more') {
			wx.showToast({
				title: '没有更多数据了...',
				icon: 'none'
			});
			return;
		}

		loadStatus.value = 'loading';
		const res = await getCategories({
			keyword: searchKeyword.value.trim(),
			type: searchType.value,
			page,
			pageSize
		});

		if (res && res.length > 0) {
			categories.value.splice(categories.value.length, 0, ...res);
		}

		if (!res || res.length < pageSize) {
			loadStatus.value = 'no-more';
		} else {
			loadStatus.value = 'more';
		}
	};
	getListData();

	// 触底刷新数据
	const showMoreData = () => {
		if (loadStatus.value === 'more') {
			page++;
			getListData();
		}
	};

	// 计算属性：过滤后的分类列表
	const filteredCategories = computed(() => {
		if (!searchKeyword.value && !searchType.value) return categories.value;

		return categories.value.filter(cat => {
			const nameMatch = searchKeyword.value.trim() ?
				cat.name.toLowerCase().includes(searchKeyword.value.trim().toLowerCase()) : true;
			const typeMatch = searchType.value ?
				cat.type.toString() === searchType.value : true;
			return nameMatch && typeMatch;
		});
	});

	// 搜索分类
	const handleSearch = () => {
		getListData(1);
	};

	// 清空搜索
	const handleSearchClear = () => {
		searchKeyword.value = '';
		getListData(1);
	};

	const userInfo = wx.getStorageSync('userInfo') || {}
	// 显示添加弹窗
	const showAddDialog = () => {
		isEditMode.value = false;
		formData.value = {
			name: '',
			type: 1,
			sort: 1,
			status: 1,
			createUser: userInfo.empId,
			updateUser: userInfo.empId
		};
		popup.value.open();
	};

	let categoryItem = {};
	// 显示编辑弹窗
	const showEditDialog = (category) => {
		categoryItem = category;
		isEditMode.value = true;
		formData.value = {
			_id: category._id,
			name: category.name,
			type: category.type,
			sort: category.sort,
			status: category.status,
			updateUser: userInfo.empId
		};
		popup.value.open();
	};

	// 提交表单
	const submitForm = async () => {
		try {
			await form.value.validate();

			if (isEditMode.value) {
				// 更新分类
				await updateCategory(formData.value);
				categoryItem.name = formData.value.name;
				categoryItem.sort = formData.value.sort;
				categoryItem.status = formData.value.status;
				categoryItem.type = formData.value.type;
				categoryItem.updateUser = formData.value.updateUser
				uni.showToast({
					title: '修改成功',
					icon: 'success'
				});
			} else {
				// 添加分类
				await addCategory(formData.value);
				uni.showToast({
					title: '添加成功',
					icon: 'success'
				});
				getListData(1);
			}
			popup.value.close();
		} catch (error) {
			console.error('提交失败:', error);
		}
	};

	// 切换分类状态
	const toggleStatus = async (category) => {
		await updateCategory({
			_id: category._id,
			status: category.status === 1 ? 0 : 1,
			updateUser: userInfo.empId
		});
		category.status = category.status === 1 ? 0 : 1;
		uni.showToast({
			title: category.status === 1 ? '已启用' : '已禁用',
			icon: 'success'
		});
	};

	// 删除分类
	const confirmDelete = async (id) => {
		const res = await uni.showModal({
			title: '提示',
			content: '确定要删除该分类吗？',
		});
		if (res.cancel) {
			return;
		}
		await deleteCategory(id);
		getListData(1)
		uni.showToast({
			title: '删除成功',
			icon: 'success'
		});
	};

	// 格式化日期
	const formatDate = (dateString) => {
		if (!dateString) return '';
		const date = new Date(dateString);
		return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
	};

	defineExpose({
		showMoreData,
		getListData
	});
</script>

<style lang="scss" scoped>
	.category-management {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
	}

	.search-bar {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx 20rpx 20rpx;
		background-color: #ffffff;
		border-bottom: 1rpx solid #eee;
		box-sizing: border-box;
		width: 100%;
		height: 150rpx;
		position: fixed;
		top: 80rpx;
		left: 0;
		z-index: 5;

		.type-select {
			display: flex;
			flex-direction: column;
			justify-content: center;
			height: 100%;
			width: 220rpx;
			// margin-left: 10rpx;
		}

		.add-btn {
			margin-left: 5rpx;
			font-size: 28rpx;
			height: 70rpx;
			line-height: 70rpx;
			border-radius: 8rpx;
			padding: 0 20rpx;
			background-color: #ff5a5f;
			color: white;
			font-weight: 700;
		}
	}

	.list-container {
		flex: 1;
		padding: 20rpx;
		margin-top: 225rpx;
	}

	.category-card {
		display: flex;
		flex-direction: row;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 15rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

		.card-left {
			width: 80%;

			.card-header {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;

				.name {
					font-size: 32rpx;
					font-weight: bold;
					margin-right: 16rpx;

					.no {
						display: inline-flex;
						font-size: 28rpx;
						width: 40rpx;
						border-radius: 25rpx;
						justify-content: center;
						align-items: center;
						color: #fa8c16;
						line-height: 100%;
					}
				}

				.type {
					font-size: 24rpx;
					padding: 4rpx 12rpx;
					border-radius: 8rpx;
					margin-right: 16rpx;

					&.dish-type {
						color: #52c41a;
					}

					&.setmeal-type {
						color: #fa8c16;
					}
				}

				.status {
					padding: 2rpx 4rpx;
					border-radius: 4rpx;
					font-size: 24rpx;
					background-color: #52c41a;
					color: #fff;

					&.status-disabled {
						background-color: #fa8c16;
						color: #fff;
					}
				}
			}

			.card-body {
				display: flex;
				flex-direction: column;
				justify-content: space-evenly;
				gap: 8rpx;

				.info-item {
					display: flex;
					align-items: center;
					margin-bottom: 12rpx;
					font-size: 26rpx;
					color: #666;

					uni-icons {
						margin-right: 8rpx;
						color: #999;
					}
				}
			}
		}

		.card-right {
			width: 20%;
			display: flex;
			flex-direction: column;
			justify-content: space-evenly;
			align-items: flex-end;

			.action-btn {
				margin: 4rpx 0;
				font-size: 26rpx;
				height: 60rpx;
				line-height: 60rpx;
				border-radius: 8rpx;
				padding: 0 20rpx;

				&.edit-btn {
					background-color: #eee;
					color: #999;
				}

				&.delete-btn {
					background-color: #ff5a5f;
					color: #fff;
					font-weight: 700;
				}
			}
		}
	}

	.safe-area-box {
		height: env(safe-area-inset-bottom);
	}

	.popup-content {
		background-color: #fff;
		width: 80vw;
		padding: 30rpx;
		border-radius: 20rpx;

		.title-box {
			box-sizing: border-box;
			display: flex;
			width: 100%;
			justify-content: center;
			padding: 40rpx 0;

			.title-text {
				font-size: 40rpx;
				font-weight: 800;
				color: #666;
			}
		}

		.form-container {
			padding: 20rpx;
		}

		.dialog-buttons {
			display: flex;
			justify-content: space-between;
			margin-top: 40rpx;

			.dialog-btn {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 8rpx;
				font-size: 28rpx;

				&.cancel-btn {
					background-color: #eee;
					color: #999;
					margin-right: 20rpx;
				}

				&.confirm-btn {
					background-color: #ff5a5f;
					color: #fff;
					font-weight: 700;
				}
			}
		}
	}
</style>